"""
预览界面模块

该模块实现相机的预览界面,包括:
- 实时预览显示
- 拍照功能
- 参数调整
"""

from drivers.display import ST7789Display
from drivers.button import Button
from drivers.camera import Camera
from config import DISPLAY_CONFIG, SYSTEM_CONFIG
import time
import logging

logger = logging.getLogger(__name__)

class Preview:
    """预览界面类"""
    
    def __init__(self, display: ST7789Display, camera: Camera, btn1: Button, btn2: Button, btn3: Button):
        """初始化预览界面
        
        参数:
            display: 显示屏对象
            camera: 相机对象
            btn1: 菜单按键对象
            btn2: 参数调整按键对象
            btn3: 拍照按键对象
        """
        self.display = display
        self.camera = camera
        self.btn1 = btn1  # 菜单键
        self.btn2 = btn2  # 参数调整键
        self.btn3 = btn3  # 拍照键
        
    def show_preview(self):
        """显示预览画面"""
        try:
            frame = self.camera.get_preview()
            if frame:
                self.display.show_image(frame)
                time.sleep_ms(1000 // SYSTEM_CONFIG['preview_fps'])
        except Exception as e:
            logger.error(f"预览显示错误: {str(e)}")
            
    def capture_photo(self):
        """拍照"""
        # 拍摄照片
        photo = self.camera.capture()
        if photo:
            # 临时显示拍照成功提示
            self.display.text("拍照成功!", 10, 10, 0xFFFF)
            self.display.show()
            return photo
        return None
            
    def handle_input(self):
        """处理按键输入"""
        if self.btn1.is_pressed():  # 菜单键
            return "menu"
        elif self.btn2.is_pressed():  # 参数调整键
            return "settings"
        elif self.btn3.is_pressed():  # 拍照键
            return self.capture_photo()
        return None
        
    def run(self):
        """运行预览界面"""
        while True:
            # 显示预览
            self.show_preview()
            
            # 处理输入
            result = self.handle_input()
            if result:
                return result
